package com.example.demo.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.http.server.HttpServerResponse;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.catalina.filters.ExpiresFilter;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    // 上传路径
    @Value("${upload.path}")

    private String uploadPath;

    @PostMapping("/upload")
    public String uploadFile(MultipartFile file) {
        File f = new File(uploadPath);
        // 创建一个抽象路径的目录，包括所有必须不存在的父目录
        if (!f.exists()) {
            f.mkdir();
        }

        // 文件的名称
        String fileName = UUID.randomUUID().toString();

        try (
                // 输入框
                InputStream in = file.getInputStream();
                // 输出流
                OutputStream out = new FileOutputStream(new File(f, fileName));
        ) {
            // 文件拷贝
            IOUtils.copy(in, out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 文件下载
    @GetMapping("/download")
    public void downLoadFile(String fileName, HttpServletResponse response) {
        try (
                // 输入
                InputStream in = new FileInputStream(new File(uploadPath, fileName));
                // 输出
                OutputStream out = response.getOutputStream();
        ) {
            // 文件拷贝
            IoUtil.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
